const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CommentModel = require('./Comment').model;

const modelName = 'News';

const NewsSchema = new Schema({
  title: { type: String, default: '标题' },
  description: { type: String, default: '内容未编辑。' },
  date: { type: Date, default() { return Date.now(); } },
  comments: {
    type: [ { type: Schema.Types.ObjectId, ref: 'Comment' } ],
    default() {
      return [];
    },
  },
}, {
  timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' }
});

NewsSchema.statics.createNews = async function(news) {
  return await new News(news).save();
}

NewsSchema.statics.obtainNews = async function(_id) {
  return await News.findById(_id).populate('comments');
}

NewsSchema.statics.obtainAllNews = async function(withComments=false) {
  const q = News.find({});
  if (withComments) {
    q.populate('comments');
  }
  return await q;
}

NewsSchema.statics.createComment = async function(_id, from, commentData) {
  const commentDoc = await CommentModel.createComment({
    refNewsId: _id,
    from: from,
    data: commentData,
  });
  const newsDoc = await News.findById(_id);
  newsDoc.comments.push(commentDoc._id);
  await newsDoc.save();
  return {
    news: newsDoc,
    resultedComment: commentDoc,
  };
}

NewsSchema.options.toJSON = {
  transform: function(doc, ret, options) {
      return ret;
  }
};

const News = mongoose.model(modelName, NewsSchema);

exports.model = News;